package com.wc.dao.impl;

import com.wc.dao.UserDao;
import com.wc.domain.User;
import com.wc.utils.JdbcUtil;
import com.wc.vo.UserVO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hc
 * @date 2022/4/9 16:33
 */
public class UserDaoImpl implements UserDao {

    @Override
    public int selectCount() throws SQLException {
        int count = 0;
        Connection conn = JdbcUtil.getConnection();
        String sql = "select count(*) count from tb_user";
        PreparedStatement ps = conn.prepareStatement(sql);

        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            count = rs.getInt("count");
        }
        JdbcUtil.release(conn, ps, rs);
        return count;
    }

    @Override
    public List<User> selectPage(Integer pageNum, Integer pageSize) throws SQLException {
        List<User> res = new ArrayList<>();

        Connection conn = JdbcUtil.getConnection();
        String sql = "select * from  tb_user limit ?, ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, (pageNum - 1) * pageSize);
        ps.setInt(2, pageSize);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            boolean gender = rs.getBoolean("gender");
            String tel = rs.getString("tel");
            int credits = rs.getInt("credits");
            User user = new User(id, name, gender, tel, credits);
            res.add(user);
        }
        JdbcUtil.release(conn, ps, rs);
        return res;
    }

    @Override
    public int isTelExists(String tel) throws SQLException {
        int count = -1;
        Connection conn = JdbcUtil.getConnection();
        String sql = "select count(*) count from tb_user where tel = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, tel);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            count = rs.getInt("count");
        }
        JdbcUtil.release(conn, ps, rs);
        return count;
    }

    @Override
    public int insert(User user) throws SQLException {
        Connection conn = JdbcUtil.getConnection();
        String sql = "insert into tb_user (name,gender,tel,credits) values (?,?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, user.getName());
        ps.setBoolean(2, user.getGender());
        ps.setString(3, user.getTel());
        ps.setInt(4, user.getCredits());
        int res = ps.executeUpdate();
        JdbcUtil.release(conn, ps, null);
        return res;
    }

}
